//
//  procedureDlgViewController.m
//  NvSellerShow
//
//  Created by dx on 17/1/19.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvProcedureDlgViewController.h"
#import "NvEditMediaViewController.h"
#import "NvPreviewDlgViewController.h"
#import "NvEditTrimViewController.h"
#import "NvTakeImageViewController.h"
#import "TakeVideoViewController.h"
#import "NvTransitionsViewController.h"
#import "Utils.h"

#import "NvRadiusUIView.h"
#import "NvRadiusUIButton.h"
#import "NvTextField.h"
#import "NvWindowPlayer.h"

#import "NvMakeFilmClipModel.h"
#import "NvsStreamingContext.h"
#import "NvsVideoTrack.h"
#import "NvsVideoClip.h"
#import "NvsAudioTrack.h"
#import "NvsAudioClip.h"
#import "NvDraftManager.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MediaPlayer/MediaPlayer.h>
#import "MediaModel.h"

#import "NvEditCaptionViewController.h"

#import "LLPhotoBrowser.h"
#import "UIImage+Resize.h"

@interface NvProcedureDlgViewController () <NvEditCaptionDelegate, NvEditTrimViewControllerDelegate, LLPhotoBrowserDelegate, NvTakeImageViewControllerDelegate, TakeVideoViewControllerDelegate,NvTransitionsDelegate>{
    NSInteger newClipNumber;
    NvProcedureTableViewCell *removeCell;
    NvMakeFilmClipModel *removeClipModel;
}
@property (weak, nonatomic) IBOutlet NvRadiusUIView *commonTemplateView;
@property (weak, nonatomic) IBOutlet NvRadiusUIView *musicSelectBtn;
@property (weak, nonatomic) IBOutlet NvRadiusUIButton *addWaterMarkBtn;
@property (weak, nonatomic) IBOutlet NvRadiusUIButton *setAudioValueBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet UIButton *soundView;
@property (strong, nonatomic) PHCachingImageManager *imageManager;

- (IBAction)addMoreSceneClick:(UITapGestureRecognizer *)sender;
@property (weak, nonatomic) IBOutlet UIButton *recordView;
@property (strong, nonatomic) NvsStreamingContext *streamingContext;
@property (strong, nonatomic) NvsTimeline *timeline;
@property (assign, nonatomic) NSInteger imageCount;
//用来确定片头的
@property (assign, nonatomic) NSInteger curIndex;
@property (strong, nonatomic) NSIndexPath *selectedCellIndex;//设置转场过的Cell

- (IBAction)preview:(id)sender;

@end

@implementation NvProcedureDlgViewController


- (PHCachingImageManager *)imageManager
{
    if (_imageManager == nil) {
        _imageManager = [PHCachingImageManager new];
    }
    
    return _imageManager;
}

- (NvsStreamingContext *)streamingContext {
    if(_streamingContext == nil) {
        _streamingContext = [NvsStreamingContext sharedInstanceWithFlags:NvsStreamingContextFlag_Support4KEdit];
    }
    return _streamingContext;
}

- (NvsTimeline *)timeline {
    if(_timeline == nil) {
        NvsVideoResolution videoEditRes;
        if(self.editmode == NvSSVideoCreateScaleSquare) {
            videoEditRes.imageWidth = 720;
            videoEditRes.imageHeight = 720;
        }else if(self.editmode == NvSSVideoCreateScaleHorizontal){
            videoEditRes.imageWidth = 1280;
            videoEditRes.imageHeight = 720;
        } else {
            videoEditRes.imageWidth = 720;
            videoEditRes.imageHeight = 1280;
        }
        
        videoEditRes.imagePAR = (NvsRational){1, 1};
        
        NvsRational videoFps = {25, 1};
        NvsAudioResolution audioEditRes;
        audioEditRes.sampleRate = 48000;
        audioEditRes.channelCount = 2;
        audioEditRes.sampleFormat = NvsAudSmpFmt_S16;
        _timeline = [self.streamingContext createTimeline:&videoEditRes videoFps:&videoFps audioEditRes:&audioEditRes];
    }
    return _timeline;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.nextBtn.enabled = NO;
    [self initData];
    [self initDataModels];
    [self setUpUI];
    [self initNavigationBarView];
    self.imageCount = 0;
    // Do any additional setup after loading the view.
}

- (void)initNavigationBarView {
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [backBtn setBackgroundImage:[UIImage imageFromBundle:@"back_icon"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    
    self.nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextBtn.frame = CGRectMake(self.view.width_LL-60, 0, 60, 44);
    [self.nextBtn setTitleColor:UIColorHexRGB(@"#3F80FF") forState:UIControlStateNormal];
    [self.nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    [self.nextBtn addTarget:self action:@selector(next:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.nextBtn];
    
    self.title = @"影片制作";
}


-(void)initData
{
    _soundVolumn = @1;
    _recordVolumn = @1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setUpUI
{
    [self updateThemeLabel];
    [self updateMusicLabel];
    [self updateVolumeLabel];
}

- (void)updateThemeLabel {
    if(self.themeName) {
        self.commonTemplateView.labelText = self.themeName;
    }
}
- (void)updateMusicLabel {
    if(self.bgMusicPath && self.bgMusicTitle) {
        _musicSelectBtn.labelText = self.bgMusicTitle;
    } else {
        _musicSelectBtn.labelText = @"选择背景音乐";
    }
    
    self.musicSelectBtn.imageRect = CGRectMake((SCREEN_WIDTH-150)/2, 13, 22, 22);
    self.musicSelectBtn.labelRect = CGRectMake((SCREEN_WIDTH-150)/2+26, 8, 120, 30);
}

- (void)updateVolumeLabel {
    if(_soundVolumn == nil) {
        _soundVolumn = [NSNumber numberWithFloat:1];
    }
    if(_recordVolumn == nil) {
        _recordVolumn = [NSNumber numberWithFloat:1];
    }
    
    [self.soundView setTitle:[NSString stringWithFormat:@"%.f%%",_soundVolumn.floatValue*100] forState:UIControlStateNormal];
    [self.recordView setTitle:[NSString stringWithFormat:@"%.f%%",_recordVolumn.floatValue*100] forState:UIControlStateNormal];
}

- (void)backBtnTouchUpInside:(id)sender {
    [self.streamingContext removeTimeline:self.timeline];
    if(self.delegate && [self.delegate respondsToSelector:@selector(nvProcedureDlgViewControllerPoped:)] == YES) {
        [self.delegate nvProcedureDlgViewControllerPoped:self];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)musicSelectBtnPressed:(id)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"MusicSelection" bundle:myBundle];
    self.definesPresentationContext = YES;
    NvMusicSelectionViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvMusicSelectionViewController"];
    modalView.delegate = self;
    if(_bgMusicTitle.length > 0)
    {
        NSLog(@"背景音乐时长:%@",_bgMusicTrimOut);
        modalView.songURL = _bgMusicPath;
        modalView.songTitle = _bgMusicTitle;
        modalView.startTime = _bgMusicTrimIn;
        modalView.endTime = _bgMusicTrimOut;
    }
    [self.navigationController pushViewController:modalView animated:YES];
}

- (void)buildTimeline {
    if([self.timeline getCurrentThemeId]) {
        [self.timeline removeCurrentTheme];
    }
    if(self.timeline.videoTrackCount == 0) {
        [self.timeline appendVideoTrack];
    }
    NvsVideoTrack *videoTrack =  [self.timeline getVideoTrackByIndex:0];
    [videoTrack removeAllClips];
    for(NvMakeFilmClipModel *model in self.modelArray){
        if(model.clipPath && model.clipType != NvClipNone){
            //clip is a images
            NvsVideoClip *videoClip = nil;
            if(model.clipType == NvClipVideo) {
                //has no trim in and trim out
                if(model.triminTimeStamp.longLongValue == 0 && model.trimoutTimeStamp.longLongValue == 0)
                    videoClip = [videoTrack appendClip:model.clipPath];
                else
                    videoClip = [videoTrack appendClip:model.clipPath trimIn:model.triminTimeStamp.longLongValue trimOut:model.trimoutTimeStamp.longLongValue];
            }
            else {
                if(model.imageDuration.intValue == 0)
                    videoClip = [videoTrack appendClip:model.clipPath];
                else
                    videoClip = [videoTrack appendClip:model.clipPath trimIn:0 trimOut:model.imageDuration.intValue * NS_TIME_BASE];
            }
            
            model.NvsClip = videoClip;
            if(model.audioVolumn.floatValue != -1 && videoClip)
            {
                [videoClip setVolumeGain:model.audioVolumn.floatValue rightVolumeGain:model.audioVolumn.floatValue];
            }
            
            if (model.pan && model.pan.floatValue != -2 && model.scan && model.scan.floatValue != -2) {
                [videoClip setPan:model.pan.floatValue andScan:model.scan.floatValue];
            }
            [videoClip changeSpeed:model.videoSpeed.floatValue];
        }
    }
    [videoTrack setVolumeGain:_recordVolumn.floatValue rightVolumeGain:_recordVolumn.floatValue];
    [self applyTheme];
    [self applyCaptionStyle];
    [self applyVideoFx];
    [self applySticker];
    [self applyMusic];
    [self applyTransitionWithVideoTrack:videoTrack];
}

- (void)applyVideoFx {
    for(NvMakeFilmClipModel *model in self.modelArray){
        if (model.clipPath && model.clipType != NvClipNone) {
            //删除内置特效
            NSArray *array = [self.timeline getTimelineVideoFxByTimelinePosition:model.NvsClip.inPoint];
            NvsTimelineVideoFx *videoFx = [array firstObject];
            [self.timeline removeTimelineVideoFx:videoFx];
            if (![model.videoFx isEqualToString:@"None"]) {
                // 添加内置特效
                [self.timeline addBuiltinTimelineVideoFx:model.NvsClip.inPoint duration:model.NvsClip.outPoint-model.NvsClip.inPoint videoFxName:model.videoFx];
            } 
        }
    }
}

- (void)applyCaptionStyle {
    for(NvMakeFilmClipModel *model in self.modelArray){
        if(model.clipPath && model.clipType != NvClipNone){
            if(model.clipCaption != nil && model.clipCaption.length && model.NvsClip) {
                NSString *captionStyleId = model.captionStyleId;
                if(self.themeUuid && [self.timeline getCurrentThemeId] && model.captionStyleId.length == 0) {
                    captionStyleId = @"theme";
                }
                [self.timeline addCaption:model.clipCaption inPoint:model.NvsClip.inPoint duration:model.NvsClip.outPoint - model.NvsClip.inPoint captionStylePackageId:captionStyleId];
            }
            NSArray *array = [self.timeline getCaptionsByTimelinePosition:model.NvsClip.inPoint];
            NvsTimelineCaption *caption = [array firstObject];
            if (model.captionOffset != nil) {
                [caption translateCaption:CGPointFromString(model.captionOffset)];
                if (model.captionScale != nil) {
                    CGPoint center = [self getCenterWithArray:[caption getBoundingRectangleVertices]];
                    [caption scaleCaption:model.captionScale.floatValue anchor:center];
                }
            }
        }
    }
}

- (void)applySticker {
    for(NvMakeFilmClipModel *model in self.modelArray){
        if(model.clipPath && model.clipType != NvClipNone){
            //none sticker
            if(model.stickerPackageId == nil || [model.stickerPackageId isEqualToString:@""]) {
                //do nothing
            }
            else {
                [_timeline addAnimatedSticker:model.NvsClip.inPoint duration:model.NvsClip.outPoint - model.NvsClip.inPoint animatedStickerPackageId:model.stickerPackageId];
            }
            NSArray *array = [self.timeline getAnimatedStickersByTimelinePosition:model.NvsClip.inPoint];
            NvsTimelineAnimatedSticker *sticker = [array firstObject];
            if (model.captionOffset != nil) {
                CGPoint offsetPoint = CGPointFromString(model.stickerOffset);
                [sticker translateAnimatedSticker:offsetPoint];
                if (model.stickerScale != nil) {
                    [sticker setScale:model.stickerScale.floatValue];
                }
            }
        }
    }
}

- (void)applyTheme {
    if(self.themeUuid && ![self.timeline getCurrentThemeId])
        [self.timeline applyTheme:self.themeUuid];
}

- (void)applyMusic {
    NSLog(@"audio track count: %d", _timeline.audioTrackCount);
    if(self.timeline.audioTrackCount)
        [self.timeline removeAudioTrack:0];
    
    float bgMusicLengthInSeconds = (self.bgMusicTrimOut.floatValue - self.bgMusicTrimIn.floatValue);
    if(self.bgMusicPath != nil && bgMusicLengthInSeconds > 0) {
        NvsAudioTrack *bgMusicTrack = [self.timeline appendAudioTrack];
        int64_t timelineDuration = self.timeline.duration;
        int64_t bgMusicLength = bgMusicLengthInSeconds * NS_TIME_BASE;
        int64_t remainDuration = timelineDuration - 2000000;
        while (remainDuration > bgMusicLength) {
            [bgMusicTrack appendClip:self.bgMusicPath trimIn:self.bgMusicTrimIn.floatValue * NS_TIME_BASE trimOut:self.bgMusicTrimOut.floatValue * NS_TIME_BASE];
            remainDuration -= bgMusicLength;
        }
        [bgMusicTrack appendClip:self.bgMusicPath trimIn:self.bgMusicTrimIn.floatValue * NS_TIME_BASE trimOut:self.bgMusicTrimIn.floatValue * NS_TIME_BASE + remainDuration];
        [bgMusicTrack setVolumeGain:_soundVolumn.floatValue rightVolumeGain:_soundVolumn.floatValue];
        [self.timeline setThemeMusicVolumeGain:0 rightVolumeGain:0];
    }
    else {
        [self.timeline setThemeMusicVolumeGain:_soundVolumn.floatValue rightVolumeGain:_soundVolumn.floatValue];
    }
}

-(void)applyTransitionWithVideoTrack:(NvsVideoTrack *)videoTrack{
    for (unsigned int i = 0; i<videoTrack.clipCount; i++) {
        if (i >= 1) {
            NvMakeFilmClipModel *model = self.modelArray[i];
            [videoTrack setBuiltinTransition:i-1 withName:model.transitionModel.transitionName];
        }
    }
}

- (void)next:(id)sender {
    if (![self checkVideoHeader]) {
        return;
    }
    if(![self checkTimeLineDuration])
        return;
    
    NSDictionary *dict = [self createDraftModel];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"CompileAndSave" bundle:myBundle];
    self.definesPresentationContext = YES;
    NvCompileAndSaveViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvCompileAndSaveViewController"];
    modalView.editmode = _editmode;
    modalView.streamingContext = self.streamingContext;
    modalView.timeline = self.timeline;
    modalView.modelUUID = self.themeUuid;
    modalView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    modalView.draftDict = dict;
    [self.navigationController pushViewController:modalView animated:YES];
}

//检查有效素材
- (BOOL)hasValidClip {
    [self buildTimeline];
    BOOL hasClip = NO;
    NvsVideoTrack * videoTrcak = [self.timeline getVideoTrackByIndex:0];
    if(videoTrcak) {
        for (unsigned int i = 1; i < videoTrcak.clipCount; i++) {
            NvsVideoClip *tempClip = [videoTrcak getClipWithIndex:i];
            if (tempClip.roleInTheme != NvsRoleInThemeGeneral) {
                continue;
            }
            hasClip = YES;
            break;
        }
    }
    return hasClip;
}

- (NvsClip *) findNvsClipWithClipPath:(NSString *)clipPath {
    NvsVideoTrack * videoTrcak = [self.timeline getVideoTrackByIndex:0];
    if(videoTrcak) {
        for (unsigned int i = 0; i < videoTrcak.clipCount; i++)
        {
            NvsVideoClip *tempClip = [videoTrcak getClipWithIndex:i];
            if ([tempClip.filePath isEqualToString: clipPath]) {
                return tempClip;
            }
        }
    }
    return nil;
}

- (BOOL)hasVideoHeader {
    NvMakeFilmClipModel *model = [self.modelArray objectAtIndex:0];
    if (model.clipThumb != nil) {
        return YES;
    }
    return NO;
}

- (BOOL)checkVideoHeader {
    BOOL hasHeader = [self hasVideoHeader];
    
    if (!hasHeader) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前无片头" message:@"请添加有效的片头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return  NO;
    }
    return YES;
}

- (BOOL)checkTimeLineDuration {
    BOOL hasClip = [self hasValidClip];
    
    if(!hasClip) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前无素材" message:@"请添加有效的素材" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    return YES;
}

- (IBAction)preview:(UIButton *)sender {
    if (![self checkVideoHeader]) {
        return;
    }
    if(![self checkTimeLineDuration]) {
        return;
    }
    
    NvPreviewDlgViewController *modalView = [NvPreviewDlgViewController new];
    modalView.streamingContext = self.streamingContext;
    modalView.timeline = self.timeline;
    modalView.editmode = self.editmode;
    
    [self.navigationController pushViewController:modalView animated:YES];
}

#pragma mark - implement TableView delegate

-(void)initDataModels {
    _modelArray = [[NSMutableArray alloc] init];
    NvMakeFilmClipModel *model;
    
    //if have draft
    if(self.draftDictionary) {
        [self readDraft];
        self.nextBtn.enabled = YES;
        return;
    }
    
    if(_editmode == NvSSVideoCreateScaleHorizontal &&([self.themeUuid isEqualToString:@"DA8443F4-135F-4CA2-9F90-5F5BD0E062DA" ]||[self.themeUuid isEqualToString:@"8F42EBB8-1E61-42CD-A3F3-45BCEB9BCA83"])){
        
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"片头介绍"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"汽车正面"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"汽车斜向45°"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"汽车侧面"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"汽车背面"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"汽车中控台"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"汽车后背箱"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"使用说明"];
        [_modelArray addObject:model];
        
    } else {
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"片头介绍"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"物品正面"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"物品斜向45°"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"物品侧面"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"物品背面"];
        [_modelArray addObject:model];
        model = [[NvMakeFilmClipModel alloc] initWithTitle:@"使用说明"];
        [_modelArray addObject:model];
    }
}


- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _modelArray.count;
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * originCellIdentifier = @"NvProcedureTableViewOriginCell";
    static NSString * addedCellIdentifier = @"NvProcedureTableViewCell";
    NvMakeFilmClipModel *model = [_modelArray objectAtIndex:indexPath.row];
    if(model.modelType == NvMakeFilmClipModelOrigin){
        NvProcedureTableViewOriginCell * originCell = [tableView dequeueReusableCellWithIdentifier:originCellIdentifier];
        if(originCell == nil){
            NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
            NSBundle *myBundle = [NSBundle bundleWithPath:path];
            originCell= [[myBundle loadNibNamed:originCellIdentifier owner:nil options:nil] firstObject];
        }
        originCell.selectionStyle = UITableViewCellSelectionStyleNone;
        originCell.numberLabel.text = [NSString stringWithFormat:@"%@", @(indexPath.row + 1)];
        originCell.titleLabel.text = model.clipTitle;
        originCell.clipModel = model;
        originCell.delegate = self;
        return originCell;
    } else {
        NvProcedureTableViewCell * addedCell = [tableView dequeueReusableCellWithIdentifier:addedCellIdentifier];
        if(addedCell == nil){
            NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
            NSBundle *myBundle = [NSBundle bundleWithPath:path];
            addedCell= [[myBundle loadNibNamed:addedCellIdentifier owner:nil options:nil] firstObject];
        }
        addedCell.selectionStyle = UITableViewCellSelectionStyleNone;
        [addedCell.thumbView setImage:model.clipThumb];
        addedCell.numberLabel.text = [NSString stringWithFormat:@"%@", @(indexPath.row + 1)];
        addedCell.titleLabel.text = model.clipTitle;
        addedCell.clipModel = model;
        addedCell.delegate = self;
        if (model.transitionModel.cellImageName) {
            [addedCell.cuttoButton setImage:[UIImage imageFromBundle:model.transitionModel.cellImageName] forState:UIControlStateNormal];
        }else{
            [addedCell.cuttoButton setImage:[UIImage imageFromBundle:@"无转场"] forState:UIControlStateNormal];
        }
        if (indexPath.row == 0) {
            [addedCell.cuttoButton setHidden:YES];
        }else{
            [addedCell.cuttoButton setHidden:NO];
        }
        if (model.clipType == NvClipImage) {
            [addedCell.videoSeeImageView setHidden:YES];
        }else{
            [addedCell.videoSeeImageView setHidden:NO];
        }
        return addedCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NvMakeFilmClipModel *model = [_modelArray objectAtIndex:indexPath.row];
    if(model.modelType == NvMakeFilmClipModelOrigin)
        return 65;
    else
        return 187;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 1;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//
//    return 58;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//
//    UIView *footerView = [[UIView alloc] init];
//
//    footerView.userInteractionEnabled = YES;
//    footerView.backgroundColor = [UIColor clearColor];
//    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [addButton setBackgroundColor:[UIColor colorWithHexString:@"#ffffff"]];
//    [addButton setTitle:@"添加更多镜头" forState:UIControlStateNormal];
//    [addButton setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateNormal];
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
//    NSBundle *myBundle = [NSBundle bundleWithPath:path];
//    UIImage *addImage = [UIImage imageWithContentsOfFile:[myBundle pathForResource:@"make_add" ofType:@"png"]];
//    [addButton setImage:addImage forState: UIControlStateNormal];
//    [addButton setTranslatesAutoresizingMaskIntoConstraints:NO];
//    [addButton addTarget:self action:@selector(addButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    [footerView addSubview:addButton];
//
//    NSDictionary *constraintsView = NSDictionaryOfVariableBindings(addButton);
//
//    [footerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[addButton]-0-|"  options:0 metrics:nil views:constraintsView ]];
//    [footerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[addButton]-0-|"    options:0 metrics:nil views:constraintsView]];
//    return footerView;
//}



#pragma mark - show QBImagePickerController

- (void)showQBImagePickerController {
    QBImagePickerController *imagePickerController = [QBImagePickerController new];
    imagePickerController.delegate = self;
    NSString *prompt;
    prompt = @"请选择图片视频";
    imagePickerController.mediaType = QBImagePickerMediaTypeAny;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 1;
    imagePickerController.prompt = prompt;
    imagePickerController.showsNumberOfSelectedAssets = YES;
    [self presentViewController:imagePickerController animated:YES completion:NULL];
}


#pragma mark - implement TableViewOriginCellDelete

- (void)nvProcedureTableViewOriginCell:(NvProcedureTableViewOriginCell *)cell addClipFromCameraForNvMakeFilmClipModel:(NvMakeFilmClipModel *)clipModel {
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相册权限" message:@"设置-隐私-照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    self.curIndex = cell.numberLabel.text.integerValue;
    if(self.editmode == NvSSVideoCreateScaleSquare) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"TakeMediaDlg" bundle:myBundle];
        self.definesPresentationContext = YES;
        NvTakeMediaViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvTakeMediaViewController"];
        self.editingModel = clipModel;
        modalView.delegate = self;
        [self presentViewController:modalView animated:YES completion:nil];
        
        NSLog(@"add clip from camara for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
        
    } else if(self.editmode == NvSSVideoCreateScaleHorizontal){
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"NvTakeImage" bundle:myBundle];
        self.definesPresentationContext = YES;
        NvTakeImageViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvTakeImage"];
        modalView.delegate = self;
        modalView.editmode = self.editmode;
        self.editingModel = clipModel;
        [self presentViewController:modalView animated:YES completion:nil];
        NSLog(@"add clip from camara for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
        
    } else if (self.editmode == NvSSVideoCreateScaleVertical) {
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
        NSBundle *myBundle = [NSBundle bundleWithPath:path];
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"NvTakeImage" bundle:myBundle];
        self.definesPresentationContext = YES;
        NvTakeImageViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvTakeImage"];
        modalView.delegate = self;
        modalView.editmode = self.editmode;
        self.editingModel = clipModel;
        [self presentViewController:modalView animated:YES completion:nil];
        NSLog(@"add clip from camara for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
        
    }
}

- (void)nvProcedureTableViewOriginCell:(NvProcedureTableViewOriginCell *)cell addClipFromRecordForNvMakeFilmClipModel: (NvMakeFilmClipModel *) clipModel {
//    BOOL canCa = [self canUseCamera];
//    if (!canCa) {
//        return ;
//    }
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相册权限" message:@"设置-隐私-照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    if(self.editmode == NvSSVideoCreateScaleSquare) {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"NvTakeVideo" bundle:myBundle];
        self.definesPresentationContext = YES;
        TakeVideoViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvTakeVideo"];
        self.editingModel = clipModel;
        modalView.delegate = self;
        modalView.editmode = self.editmode;
        [self presentViewController:modalView animated:YES completion:nil];
        NSLog(@"add clip from camara for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
    } else {
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"TakeVideoDlg" bundle:myBundle];
        self.definesPresentationContext = YES;
        NvTakeVideoViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvTakeVideoViewController"];
        modalView.clipModel = clipModel;
        self.editingModel = clipModel;
        modalView.delegate = self;
        modalView.editmode = self.editmode;
        [self presentViewController:modalView animated:YES completion:nil];
        NSLog(@"add clip from camara for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
        
    }
}

#pragma mark - 检查相机权限
- (BOOL)canUseCamera{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else{
        return YES;
    }
}


#pragma mark - 检查相册权限
- (BOOL)canUsePhotoAlbum{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开照片权限" message:@"设置-隐私-照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    return YES;
}

- (void)nvProcedureTableViewOriginCell:(NvProcedureTableViewOriginCell *)cell addClipFromPhotoForNvMakeFilmClipModel:(NvMakeFilmClipModel *)clipModel {
    self.curIndex = cell.numberLabel.text.integerValue;
    NSLog(@"add clip from photo for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
    self.editingModel = clipModel;
    ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请打开相册权限" message:@"设置-隐私-照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    [self showQBImagePickerController];
}

- (NSIndexPath *)getCellIndexPath:(NvProcedureTableViewCell *)cell {
    return [self.tableView indexPathForCell:cell];
}

- (CGPoint)getCenterWithArray:(NSArray*)array {
    NSValue *leftTopValue = array[0];
    NSValue *rightBottomValue = array[2];
    CGPoint topLeftCorner = [leftTopValue CGPointValue];
    CGPoint rightBottomCorner = [rightBottomValue CGPointValue];
    return CGPointMake((topLeftCorner.x+rightBottomCorner.x)/2, (topLeftCorner.y+rightBottomCorner.y)/2);
}

#pragma mark - 检查图片是否超过3张
- (BOOL)checkImageCount {
    NSLog(@"添加一张图片");
    if (self.imageCount > 3) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"图片超过三张建议拍摄视频" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return YES;
    }
    return false;
}

#pragma mark - implement TableViewCellDelete

- (void)nvProcedureTableViewCell:(NvProcedureTableViewCell *)cell cleanClipForNvMakeFilmClipModel:(NvMakeFilmClipModel *)clipModel {
    removeCell = cell;
    removeClipModel = clipModel;
    UIAlertView *removeAlert = [[UIAlertView alloc] initWithTitle:@"清除确定" message:@"确定要清除掉添加的素材吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [removeAlert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex==1) {//确定按钮被点击
        NvProcedureTableViewCell *cell = removeCell;
        NvMakeFilmClipModel *clipModel = removeClipModel;
        [self doCleanClipInCell:cell forClipModel:clipModel];
    }
}

- (void)doCleanClipInCell:(NvProcedureTableViewCell *)cell forClipModel:(NvMakeFilmClipModel *)clipModel {
    NSLog(@"clean clip for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
    if (clipModel.clipType == NvClipImage && cell.numberLabel.text.integerValue != 1) {
        self.imageCount--;
        NSLog(@"去掉了一张图片");
    }
    [clipModel reset];
    [self.tableView reloadRowsAtIndexPaths:@[[self getCellIndexPath:cell]] withRowAnimation:UITableViewRowAnimationAutomatic];
}



- (BOOL)decideClipExistTip:(NvMakeFilmClipModel *)clipModel {
    BOOL fileExist;
    NSString *assetsPath = clipModel.clipPath;
    if(clipModel.clipType == NvClipVideo) {
        AVAsset *asset = [AVAsset assetWithURL:[NSURL URLWithString:assetsPath]];
        NSUInteger count = [asset tracks].count;
        float duraton = (float)[asset duration].value / (float)[asset duration].timescale;
        fileExist = count == 0 || duraton == 0 ? NO : YES;
    } else {
        fileExist = [Utils checkFileExist:assetsPath];
    }
    if(!fileExist) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"素材已失效" message:@"请清除后重新选择素材" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
    return fileExist;
}



- (void)nvProcedureTableViewCell:(NvProcedureTableViewCell *)cell editCapationForNvMakeFilmClipModel:(NvMakeFilmClipModel *)clipModel {
    
    NSLog(@"edit capation for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
    
    if(![self decideClipExistTip:clipModel])
        return;
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"NvEditCaption" bundle:myBundle];
    self.definesPresentationContext = YES;
    NvEditCaptionViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvEditCaptionViewController"];
    
    modalView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    modalView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    modalView.clipModel = clipModel;
    modalView.themeUuid = self.themeUuid;
    modalView.editMode = self.editmode;
    modalView.delegate = self;
    
    self.editingModel = clipModel;
    
    [self.navigationController pushViewController:modalView animated:YES];
}

- (void)nvProcedureTableViewCell:(NvProcedureTableViewCell *)cell trimClipForNvMakeFilmClipModel:(NvMakeFilmClipModel *)clipModel {
    
    NSLog(@"trim clip for clip title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
    
    if(![self decideClipExistTip:clipModel])
         return;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"NvEditTrimClip" bundle:myBundle];
    
    NvEditTrimViewController *editTrimVC = [story instantiateViewControllerWithIdentifier:@"NvEditTrimViewController"];
    editTrimVC.createMode = self.editmode;
    clipModel.captionStyleId = nil;
    editTrimVC.model = clipModel;//数据
    editTrimVC.delegate = self;
    editTrimVC.clipType = clipModel.clipType;
    editTrimVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    editTrimVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    
    self.editingModel = clipModel;
    
    [self.navigationController pushViewController:editTrimVC animated:YES];
}

//跳转转场动画界面
- (void)nvProcedureTableViewCell:(NvProcedureTableViewCell *)cell cuttoCapationForNvMakeFilmClipModel:(NvMakeFilmClipModel *)clipModel {
    
    NSLog(@"cutto Capation For cutto title: %@, %@", clipModel.clipTitle, cell.numberLabel.text);
    
    if(![self decideClipExistTip:clipModel])
        return;
    //记录当前点击的Cell
    self.selectedCellIndex = [self.tableView indexPathForCell:cell];
    NvTransitionsViewController *transition = [[NvTransitionsViewController alloc]init];
    transition.editMode = self.editmode;
    transition.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    transition.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    transition.delegate = self;
    transition.transitionModel = clipModel.transitionModel;
    NSMutableArray * clipModelArray = [[NSMutableArray alloc]init];
    BOOL isData = NO;
    for (NSInteger i = self.selectedCellIndex.row-1; i >= 0; i--) {
        NvMakeFilmClipModel *clipModel = self.modelArray[i];
        if (clipModel.clipType != NvClipNone) {
            //添加第一个视频
            [clipModelArray addObject:clipModel];
            isData = YES;
            break;
        }
    }
    if (!isData) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"当前无片头" message:@"请添加有效的片头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    //添加第二个视频
    [clipModelArray addObject:self.modelArray[self.selectedCellIndex.row]];
    self.editingModel = clipModel;
    transition.clipModelArray = clipModelArray;
    [self.navigationController pushViewController:transition animated:YES];
}

#pragma mark - implement QBImagePickerControllerDelegate

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    self.editingModel = nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)setClipInfoWithAsset:(PHAsset*)asset {
    __weak __typeof(self) weakSelf = self;
    if(asset.mediaType == PHAssetMediaTypeVideo) {
        self.editingModel.modelType = NvClipVideo;
        [self.imageManager requestAVAssetForVideo:asset
                                          options:[PHVideoRequestOptions new] resultHandler:^(AVAsset * avasset, AVAudioMix * audioMix, NSDictionary * info) {
                                              dispatch_async(dispatch_get_main_queue(), ^{
                                                  [weakSelf setAssetUrlForEditingClipModel:avasset];
                                              });
                                          }];
    }
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
    
    CGSize size;
    
    // save image to sandbox
    if(asset.mediaType == PHAssetMediaTypeImage) {
        NSUInteger width = asset.pixelWidth;
        NSUInteger height = asset.pixelHeight;
        CGFloat ratio = 1.0;
        NSUInteger minum = MIN(width, height);
        if(minum > 720)
            ratio = minum / 720.0f;
        size  = CGSizeMake(width/ratio, height/ratio);
        [self.imageManager requestImageForAsset:asset
                                     targetSize: size
                                    contentMode:PHImageContentModeAspectFill
                                        options:options
                                  resultHandler:^(UIImage *image, NSDictionary *info) {
                                      
                                      NSLog(@"info: %@  %@", info, NSStringFromCGSize(image.size));
                                      if ([[info valueForKey:@"PHImageResultIsDegradedKey"]integerValue]==0){
                                          // Do something with the FULL SIZED image
                                          dispatch_async(dispatch_get_main_queue(), ^{
                                              [weakSelf setImageUrlForEditingClipModel:info image:image];
                                          });
                                      } else {
                                          // Do something with the regraded image
                                      }
                                  }];
    }
    
    //get thumb for iamge
    size  = CGSizeMake(307, 144);
    CGSize targetSize = CGSizeScale(size, [[UIScreen mainScreen] scale]);
    
    [self.imageManager requestImageForAsset:asset
                                 targetSize:targetSize
                                contentMode:PHImageContentModeAspectFit
                                    options:options
                              resultHandler:^(UIImage *thumb, NSDictionary *info) {
                                  NSLog(@"info: %@  %@", info, NSStringFromCGSize(thumb.size));
                                  if ([[info valueForKey:@"PHImageResultIsDegradedKey"]integerValue]==0){
                                      // Do something with the FULL SIZED image
                                      dispatch_async(dispatch_get_main_queue(), ^{
                                          [weakSelf setThumbForEditingClipModel:thumb];
                                      });
                                  } else {
                                      // Do something with the regraded image
                                  }
                              }];
    
    
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    PHAsset* asset = [assets firstObject];
    
    PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
    options.resizeMode = PHImageRequestOptionsResizeModeExact;
    options.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
    
    CGSize size;
    
    // save image to sandbox
    if(asset.mediaType == PHAssetMediaTypeImage) {
        NSUInteger width = asset.pixelWidth;
        NSUInteger height = asset.pixelHeight;
        size  = CGSizeMake(width, height);
        
        if (self.editmode == NvSSVideoCreateScaleSquare) {//不用剪切直接选取
            if(self.editingModel != nil) {
                PHAsset *asset = assets[0];
                [self setClipInfoWithAsset:asset];
            }
        } else if (self.editmode == NvSSVideoCreateScaleHorizontal) {//需要进行裁剪
            [self.imageManager requestImageForAsset:asset targetSize: size contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *image, NSDictionary *info) {
                NSLog(@"info: %@  %@", info, NSStringFromCGSize(image.size));
                if ([[info valueForKey:@"PHImageResultIsDegradedKey"]integerValue]==0){
                    // Do something with the FULL SIZED image
                    dispatch_async(dispatch_get_main_queue(), ^{
                        LLPhotoBrowser *llPhotoBrowser = [[LLPhotoBrowser alloc] initWithImages:@[image] currentIndex:0];
                        llPhotoBrowser.delegate = self;
                        [self presentViewController:llPhotoBrowser animated:YES completion:NULL];
                    });
                } else {
                    // Do something with the regraded image
                }
            }];
        } else {
            //            9:16
            [self.imageManager requestImageForAsset:asset targetSize: size contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *image, NSDictionary *info) {
                NSLog(@"info: %@  %@", info, NSStringFromCGSize(image.size));
                if ([[info valueForKey:@"PHImageResultIsDegradedKey"]integerValue]==0){
                    // Do something with the FULL SIZED image
                    dispatch_async(dispatch_get_main_queue(), ^{
                        LLPhotoBrowser *llPhotoBrowser = [[LLPhotoBrowser alloc] initWithImages:@[image] currentIndex:0];
                        llPhotoBrowser.delegate = self;
                        llPhotoBrowser.editmode = self.editmode;
                        [self presentViewController:llPhotoBrowser animated:YES completion:NULL];
                    });
                } else {
                    // Do something with the regraded image
                }
            }];
        }
        
    } else if(asset.mediaType == PHAssetMediaTypeVideo) {
        
        if (self.editmode == NvSSVideoCreateScaleSquare) {//需要进行裁剪
            [self.imageManager requestAVAssetForVideo:asset options:[PHVideoRequestOptions new] resultHandler:^(AVAsset * avasset, AVAudioMix * audioMix, NSDictionary * info) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    //剪辑视频
                    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
                    NSBundle *myBundle = [NSBundle bundleWithPath:path];
                    UIStoryboard *story = [UIStoryboard storyboardWithName:@"NvTakeVideo" bundle:myBundle];
                    self.definesPresentationContext = YES;
                    TakeVideoViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvTakeVideo"];
                    //如果这个属性被设置为相册则在进入视频预览时，点击取消按钮应返回
                    modalView.from = @"相册";
                    modalView.delegate = self;
                    modalView.avasset = avasset;
                    [self presentViewController:modalView animated:YES completion:nil];
                });
            }];
        } else if(self.editmode == NvSSVideoCreateScaleHorizontal){//不需要进行裁剪
            if(self.editingModel != nil) {
                PHAsset *asset = assets[0];
                [self setClipInfoWithAsset:asset];
            }
        } else {
            PHAsset *asset = assets[0];
            [self setClipInfoWithAsset:asset];
        }
        
    }
    
    [imagePickerController dismissViewControllerAnimated:YES completion:nil];
    
}

#pragma mark - Implement NvEditAudioViewControllerDelegate
- (void)didfinishSetSound:(float)sound Record:(float)record{
    _soundVolumn = [NSNumber numberWithFloat:sound];
    _recordVolumn = [NSNumber numberWithFloat:record];;
    [self updateVolumeLabel];
}

#pragma mark - implement NvTakeVideoViewControllerDelegate
- (void)takeVideoViewController:(TakeVideoViewController *)takeVideoViewController didSelectVideo:(AVAsset *)avasset pan:(float)pan scan:(float)scan{
    [takeVideoViewController dismissViewControllerAnimated:YES completion:NULL];
    [self setAssetUrlForEditingClipModel:avasset];
    
    self.editingModel.pan = [NSNumber numberWithFloat:pan];
    self.editingModel.scan = [NSNumber numberWithFloat:scan];
    
    //你试试这个行不行，我试了可以
    NSURL* assetUrl =[(AVURLAsset*)avasset URL];
    UIImage *norimage = [UIImage imageWithVideoUrl:assetUrl seekPos:5];
    norimage=[norimage normalizedImage];
    CGRect rect;
    if (norimage.size.width > norimage.size.height) {
        rect = CGRectMake((norimage.size.width-norimage.size.height)/2.0, 0, norimage.size.height, norimage.size.height);
    } else {
        rect = CGRectMake(0, (norimage.size.height-norimage.size.width)/2.0, norimage.size.width, norimage.size.width);
    }
    UIImage *img = [UIImage handleImage:norimage withFrame:rect];
    NSData *data = UIImageJPEGRepresentation(img, 0.1);
    UIImage *scaleImage = [UIImage imageWithData:data];
    [self setThumbForEditingClipModel:scaleImage];
    
}

#pragma mark - implement NvTakeImageViewControllerDelegate
-(void)nvTakeImageViewController:(NvTakeImageViewController*)nvTakeImageViewController didFinishTakeImage:(UIImage*)image {
    [nvTakeImageViewController dismissViewControllerAnimated:YES completion:NULL];
    [self setImageUrlForEditingClipModel:nil image:image];
    [self setThumbForEditingClipModel:image];
}

#pragma mark - implement NvTakeMediaViewControllerDelegate
-(void)didFinishTakeMedia:(PHAsset*)asset
{
    [self setClipInfoWithAsset:asset];
}

#pragma mark - implement NvTakeVideoViewControllerDelegate
-(void)didFinishTakeVideo:(PHAsset*)asset
{
    [self setClipInfoWithAsset:asset];
}

#pragma mark - implement NvEditCaptionDelegate
-(void)nvEditCaptionViewController:(NvEditCaptionViewController *)controller didFinishSetCaption:(NSString *)caption withCaptionStyleId:(NSString *)captionStyleId captionOffset:(NSString *)captionoffset didFinishSetStickerId:(NSString *)stickerID stickerOffset:(NSString *)stickeroffset captionScale:(CGFloat)captionscale stickerScale:(CGFloat)stickerscale{
    _editingModel.captionOffset = captionoffset;
    _editingModel.clipCaption = caption;
    _editingModel.captionStyleId = captionStyleId;
    _editingModel.stickerPackageId = stickerID;
    _editingModel.stickerOffset = stickeroffset;
    _editingModel.captionScale = [NSString stringWithFormat:@"%g",captionscale];
    _editingModel.stickerScale = [NSString stringWithFormat:@"%g",stickerscale];
}

#pragma mark - implement NvEditVideoViewDelegate
-(void)didFinishSetCaption:(NSString *)caption {
    _editingModel.clipCaption = caption;
}

-(void)didFinishSetVideoTrimIn:(NSNumber *)trimIn andTrimOut:(NSNumber *)trimOut sound:(NSNumber *)volumn videoFx:(NSString *)videoFxName videoSpeed:(NSNumber *)speed{
    _editingModel.triminTimeStamp = trimIn;
    _editingModel.trimoutTimeStamp = trimOut;
    _editingModel.audioVolumn = volumn;
    _editingModel.videoFx = videoFxName;
    _editingModel.videoSpeed = speed;
}

-(void)didFinishSetImageDuration:(NSNumber *)imageDuration sound:(NSNumber *)volumn videoFx:(NSString *)videoFxName{
    _editingModel.imageDuration = imageDuration;
    _editingModel.audioVolumn = volumn;
    _editingModel.videoFx = videoFxName;
}

#pragma mark - Implement NvTransitionsViewControllerDelegate
-(void)nvTransitionDidSelectedTransitionModel:(NvTransitionsModel *)transitionModel clipModelArray:(NSArray *)clipModelArray{
    self.editingModel.transitionModel = transitionModel;
    [self.tableView reloadData];
}

#pragma mark - Implement NvMusicSelectionViewControllerDelegate
- (void)didFinishSelectMusic:(NSString *)songTitle MusicUrl:(NSString *)songUrl StartTime:(NSNumber *)startTime EndTime:(NSNumber *)endTime{
    _bgMusicTitle = songTitle;
    _bgMusicPath = songUrl;
    _bgMusicTrimIn = startTime;
    _bgMusicTrimOut = endTime;
    [self updateMusicLabel];
}

#pragma mark - LLPhotoBrowserDelegate
- (void)photoBrowser:(LLPhotoBrowser *)photoBrowser didSelectImage:(id)image rect:(CGRect)rect {
    [photoBrowser dismissViewControllerAnimated:YES completion:NULL];
    [self setImageUrlForEditingClipModel:nil image:image];
    [self setThumbForEditingClipModel:image];
}

#pragma mark - produce phasset thumb and url
- (void)setThumbForEditingClipModel:(UIImage *)thumb{
    self.editingModel.clipThumb = thumb;
    NSLog(@"get thumb");
    
    NSInteger index = [self.modelArray indexOfObject:self.editingModel];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    if([cell isKindOfClass:[NvProcedureTableViewCell class]]) {
        [((NvProcedureTableViewCell *) cell).thumbView setImage:thumb];
    }
    [self.tableView reloadData];
}

- (void)setImageUrlForEditingClipModel:(NSDictionary*)info image:(UIImage *) image {
    if (self.curIndex != 1) {
        self.imageCount++;
        NSLog(@"添加了一张图片");
        [self checkImageCount];
    }
    self.nextBtn.enabled = YES;
    
    self.editingModel.clipPath = [self saveImageToSandBox:image];
    self.editingModel.modelType = NvMakeFilmClipModelAdded;
    self.editingModel.clipType = NvClipImage;
    NSLog(@"get imageUrl %@", self.editingModel.clipPath);
    [self.tableView reloadData];
}

- (NSString *)saveImageToSandBox:(UIImage *)image {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:NS_SCALE_IMAGE_PATH];
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL success = NO;
    if (![fileManager fileExistsAtPath:filePath])
        success = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    else
        success = YES;
    if (success) {
        NSString *imageSaveTime = [Utils getTimeAndRandom];
        NSString *path = [filePath stringByAppendingFormat:@"/%@.jpg", imageSaveTime];
        [data writeToFile:path atomically:YES];
        return path;
    }
    return nil;
}


- (void)setAssetUrlForEditingClipModel:(AVAsset *) asset{
    self.nextBtn.enabled = YES;
    
    //[asset isKindOfClass:[AVComposition class]]
    AVURLAsset *urlAsset = (AVURLAsset *)asset;
    
    self.editingModel.clipPath = [urlAsset.URL absoluteString];
    self.editingModel.modelType = NvMakeFilmClipModelAdded;
    self.editingModel.clipType = NvClipVideo;
    
    NSLog(@"get AVAsset %@", self.editingModel.clipPath);
    [self.tableView reloadData];
}

- (IBAction)audioClick:(id)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"EditAudioDlg" bundle:myBundle];
    self.definesPresentationContext = YES;
    NvEditAudioViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvEditAudioViewController"];
    modalView.delegate = self;
    [modalView setSound:_soundVolumn.floatValue];
    [modalView setRecord:_recordVolumn.floatValue];
    modalView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    modalView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:modalView animated:YES completion:nil];
}

- (IBAction)recordClick:(id)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"EditAudioDlg" bundle:myBundle];
    self.definesPresentationContext = YES;
    NvEditAudioViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvEditAudioViewController"];
    modalView.delegate = self;
    [modalView setSound:_soundVolumn.floatValue];
    [modalView setRecord:_recordVolumn.floatValue];
    modalView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    modalView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:modalView animated:YES completion:nil];
}

- (IBAction)setAudioValueBtnPressed:(id)sender {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"EditAudioDlg" bundle:myBundle];
    self.definesPresentationContext = YES;
    NvEditAudioViewController *modalView = [story instantiateViewControllerWithIdentifier:@"NvEditAudioViewController"];
    modalView.delegate = self;
    [modalView setSound:_soundVolumn.floatValue];
    [modalView setRecord:_recordVolumn.floatValue];
    modalView.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    modalView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:modalView animated:YES completion:nil];
    
}
#pragma mark - <  获取相册里的所有图片的PHAsset对象  >

-(NSMutableArray*)GetALLMedias:(PHAssetMediaType)mediaType
{
    NSMutableArray *arr = [NSMutableArray array];
    // 所有智能相册
    PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    for (NSInteger i = 0; i < smartAlbums.count; i++) {
        // 是否按创建时间排序
        PHFetchOptions *option = [[PHFetchOptions alloc] init];
        option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
        option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", mediaType];
        PHCollection *collection = smartAlbums[i];
        //遍历获取相册
        if ([collection isKindOfClass:[PHAssetCollection class]]) {
            if ([collection.localizedTitle isEqualToString:@"相机胶卷"]) {
                PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
                PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
                if (fetchResult.count > 0) {
                    // 某个相册里面的所有PHAsset对象
                    [fetchResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL * _Nonnull stop) {
                        [arr addObject:asset];
                    }];
                }
            }
        }
    }
    //返回相机胶卷内的所有资源
    return arr;
}


#pragma mark - SaveDraft and ReadDraft
- (NSDictionary *)createDraftModel {
    //检查是否有效素材
    if(![self hasValidClip])
        return nil;
    
     //判断本素材是否存在，存在的话则删除，不存在生成当前时间戳作为名称
    NSString *draftName;
    if(self.draftDictionary) {
        draftName = [self.draftDictionary valueForKey:DraftNameKey];
        [NvDraftManager deleteDraftAtIds:@[draftName]];
    } else {
        draftName = [Utils getTimeAndRandom];
    }
    
    //保存封面图数据
    NSMutableDictionary * draftDictionary = [NSMutableDictionary dictionary];
    [draftDictionary setValue:draftName forKey:DraftNameKey];
    [draftDictionary setValue:[NSDate date] forKey:DraftCreatedDateKey];
    for(NvMakeFilmClipModel *clipModel in self.modelArray) {
        if(clipModel.clipType != NvClipNone && clipModel.clipThumb != nil) {
            UIImage *draftThumb = clipModel.clipThumb;
            NSData *draftThumbData = UIImageJPEGRepresentation(draftThumb, 100);
            [draftDictionary setValue:draftThumbData forKey:DraftThumbDataKey];
            break;
        }
    }
    
    //保存页面公共数据
    [draftDictionary setValue:[NSNumber numberWithInt:self.editmode] forKey:DraftEditModeKey];
    [draftDictionary setValue:self.themeUuid forKey:DraftThemeIdKey];
    [draftDictionary setValue:self.themeName forKey:DraftThemeNameKey];
    [draftDictionary setValue:self.bgMusicPath forKey:DraftSelectedMusicPathKey];
    [draftDictionary setValue:self.bgMusicTrimIn forKey:DraftSelectedMusicTrimInKey];
    [draftDictionary setValue:self.bgMusicTrimOut forKey:DraftSelectedMusicTrimOutKey];
    [draftDictionary setValue:self.bgMusicTitle forKey:DraftSelectedMusicNameKey];
    [draftDictionary setValue:self.soundVolumn forKey:DraftMusicVolumeKey];
    [draftDictionary setValue:self.recordVolumn forKey:DraftOriginVolumeKey];
    
    //存储clipModel数据
    NSMutableArray *draftClipModelArray = [NSMutableArray array];
    for(NvMakeFilmClipModel *clipModel in self.modelArray) {
        NSDictionary * draftClip = [clipModel getDraftClipDictionary];
        [draftClipModelArray addObject:draftClip];
    }
    self.draftDictionary = draftDictionary.copy;
    [draftDictionary setValue:draftClipModelArray.copy forKey:DraftModelsArrayKey];
    return draftDictionary;
}

- (void)readDraft {
    if(!self.draftDictionary)
        return;
    //edit mode
    self.editmode =  ((NSNumber *)[self.draftDictionary valueForKey:DraftEditModeKey]).intValue;
    
    //theme
    self.themeUuid = [self.draftDictionary valueForKey:DraftThemeIdKey];
    self.themeName = [self.draftDictionary valueForKey:DraftThemeNameKey];
    
    //bgmusic
    self.bgMusicPath = [self.draftDictionary valueForKey:DraftSelectedMusicPathKey];
    if(self.bgMusicPath) {
        self.bgMusicTitle = [self.draftDictionary valueForKey:DraftSelectedMusicNameKey];
        self.bgMusicTrimIn = [self.draftDictionary valueForKey:DraftSelectedMusicTrimInKey];
        self.bgMusicTrimOut = [self.draftDictionary valueForKey:DraftSelectedMusicTrimOutKey];
    }
    
    self.soundVolumn = [self.draftDictionary valueForKey:DraftMusicVolumeKey];
    self.recordVolumn = [self.draftDictionary valueForKey:DraftOriginVolumeKey];
    NSArray *modelsArray = [self.draftDictionary valueForKey:DraftModelsArrayKey];
    
    NvMakeFilmClipModel * clipModel;
    for(NSDictionary * modelDic in modelsArray) {
        clipModel = [[NvMakeFilmClipModel alloc]initWithDraftClip:modelDic];
        [self.modelArray addObject:clipModel];
    }
}


#pragma mark - Helper methods

/** @brief Returns a customized snapshot of a given view. */
- (UIView *)customSnapshoFromView:(UIView *)inputView {
    
    // Make an image from the input view.
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Create an image view.
    UIView *snapshot = [[UIImageView alloc] initWithImage:image];
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    
    return snapshot;
}


- (IBAction)addMoreSceneClick:(UITapGestureRecognizer *)sender {
    NSInteger index = self.modelArray.count;
    
    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    
    NvMakeFilmClipModel *model = [[NvMakeFilmClipModel alloc] initWithTitle:[NSString stringWithFormat:@"新镜头%ld", (long)++newClipNumber]];
    [_modelArray addObject:model];
    
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
@end
